<template>
	<div class="vue_app myGiftCard overhid" style="position: relative;width: 100%;height: 100%;">
		<div>
			<my-header :title="'我的礼品卡'" :hasTitle="true" :hasBack="true"></my-header>
			<!--头部-->
			<span class="instructions" @click="jumpEventgiftInstrut" v-if="recordata">{{recordata.typeName}}</span>
			<tab-head :titleInfor="titleInfor" v-if="titleInfor">
			</tab-head>
		</div>
		<div class="overhid" :style="`height: ${screenHeight}px`">
			<translate-main ref='verticalScroll'>
				<ul class="giftcard_list" style="padding-bottom: 4rem;">
					<li v-for="(item,index) in initData" :key="index">
						<div class="cardli">
							<img :src="item.giftcardEntityImg||'static/image/big-giftcard.png'" />
							<div class="cardhand">
								<p>卡号：{{item.giftcardEntityCode}}</p>
								<div class="bottondiv bottmar" v-if="item.activationStatus===0">
									<span class="botton" style="float: left;" @click="jumpEventChargeOff(item)">激活充值到钱包</span>
									<span class="botton bottonred" @click="giveother(item)">转赠给好友</span>
								</div>
								<p v-if="item.activationStatus===1">激活时间：{{item.activationTm}}</p>
							</div>
						</div>
					</li>
					<div class="no_data" v-if="initData.length==0 && flag">
						<img src="static/image/no_news.png" style="width:70%;" />
						<p>暂无礼品卡相关信息</p>
					</div>
				</ul>
			</translate-main>
		</div>
		<div class="cardoperation">
			<span @click="jumpEventActivate">激活礼品卡</span><span @click="jumpEventbuycard">购买礼品卡</span>
		</div>
		<button-to-top @goTop="goTop"></button-to-top>
		<passward-panel ref="passwardPanel" @passwordPendingChange="passwordPendingChangeEvent">
		</passward-panel>
	</div>
</template>

<script>
	import MyHeader from "../header";
	import axios from "axios";
	import TranslateMain from '../../real-components/VerticalScroll';
	import ButtonToTop from '../../real-components/ButtonToTopForTest';
	import { mapGetters } from "vuex";
	import TabHead from '../../real-components/TabHeadOrder';
	import { Toast } from '@/utils/toast';
	import { showLoading, hideLoading } from "@/utils/loading";
	import passwardPanel from "../../real-components/ConfirmOrder/ConfirmOrderPursekey"; //钱包支付密码面板
	export default {
		data() {
			return {
				flag: false,
				//我的礼品卡的单个数据
				titleInfor: [{
					goodsClassId: "",
					goodsClassName: "未激活"
				}, {
					goodsClassId: "",
					goodsClassName: "已激活"
				}],
				carddata: [],
				recordata: {
					typeName: "",
					expCode: "",
				},
				//等待密码校验的对象
				pwPendingResult: {
					pwPendingState: true, //默认为true，代表在等待
					result: "initial",
					msg: ""
				},
				//分享的相关信息
				giveothertitle: '送你一张礼品卡',
				giveotherurl: '',
				giveothercontant: '',
				giveotherimg: '',
			}
		},
		components: {
			"my-header": MyHeader,
			"translate-main": TranslateMain,
			ButtonToTop,
			"tab-head": TabHead,
			"passward-panel": passwardPanel,
		},
		methods: {
			//跳转礼品卡说明页面
			jumpEventgiftInstrut() {
				this.$router.push({
					path: 'giftCardInstrut?expCode=' + this.recordata.expCode
				})
			},
			//跳转到购买礼品卡页面
			jumpEventbuycard() {
				this.$router.push({
					path: 'buyGiftCard'
				})
			},
			//跳转激活礼品卡
			jumpEventActivate() {
				this.$router.push({
					path: 'ActivateGiftCard'
				})
			},
			//跳转卡面的激活礼品卡
			jumpEventChargeOff(item) {
				if(item.activationStatus == 1) {
					return
				} else if(item.activationStatus == 0) {
					this.$router.push({
						name: 'ActivateGiftCard',
						params: {
							giftcardEntityCode: item.giftcardEntityCode,
							activationCode: item.activationCode
						}
					})
				}
			},
			//回到顶部
			goTop() {
				this.$refs.verticalScroll.goTop()
			},
			//获取数据请求
			getcarddata() {
				showLoading()
				//获取我的礼品卡的单个数据
				var sessionId = localStorage.getItem('sessionId');
				let config1 = {
					url: window.api.customer_host + '/giftCardSalesAPI/getHaveGiftCardEntityList',
					//url: 'http://172.19.4.164:33004/giftCardSalesAPI/getHaveGiftCardEntityList',
					method: 'GET',
					headers: {
						'sessionId': sessionId,
					},
				};
				axios(config1).then((res) => {
					hideLoading()
					if(res.data.data[0]) {
						this.flag = true
						this.carddata = res.data.data[0]
					}
				}).catch(err=>{
					hideLoading()
					Toast({
						duration: 2000,
						message:'请求接口失败',
						type: "fail"
					});
				})
			},
			//获取礼品卡说明
			getInstrut() {
				var sessionId = localStorage.getItem('sessionId');
				var storeCode = localStorage.getItem('storeCode');
				let config = {
					url: window.api.base_host + '/expMana/queryExplain',
					method: 'GET',
					headers: {
						'sessionId': sessionId,
					},
					params: {
						storeCode: storeCode,
						typeCode: 'EXP_GIF',
						length: 1,
					},
				};
				axios(config).then((res) => {
					var max = res.data.data[0]
					this.recordata = max
				})
			},
			//转增给他人
			//跳转分享转赠他人
			async giveother(item) {
				if(!this.passwordIsSet()) {
					this.$router.push({
						name: "SetKeyWallet",
						params: {
							goBack: true
						}
					});
					return;
				}
				/*第一步校验支付密码*/
				//开始调用密码盘输入密码
				this.$refs.passwardPanel.showOrHide();
				console.log("正在等待密码校验");
				await this.waitPasswordInputAndReg();
				console.log("等待密码校验完毕");
				/*第二部分密码解密*/
				this.getpassword(item);
			},
			//判断是否设置过密码
			passwordIsSet() {
				//1为设置过密码
				return this.userInfo.walletStatus === "1";
			},
			//等待密码校验的promise
			waitPasswordInputAndReg() {
				return new Promise((resolve, reject) => {
					this.timer = setInterval(() => {
						if(!this.pwPendingResult.pwPendingState) {
							if(this.pwPendingResult.result) {
								clearInterval(this.timer);
								this.timer = null;
								//重新置为初始状态，等待用户下一次输入
								resolve(this.pwPendingResult);
							} else {
								//密码校验失败
								this.mToastFn(this.pwPendingResult.msg);
							}
							this.pwPendingResult.pwPendingState = true;
						}
					}, 100);
				});
			},
			mToastFn(msg, duration = 1000, type = "fail") {
				Toast({
					message: msg,
					type,
					duration
				});
			},
			//当输入密码组件校验完毕后改变pending值
			passwordPendingChangeEvent(obj) {
				//接收到一个对象
				this.pwPendingResult = obj;
			},
			//分享转赠方法
			SharePlugin(sucFunc, failFunc, url, opts, className) {
				sucFunc = sucFunc || function() {};
				failFunc = failFunc || function() {};
				//url = url || 'Share';
				opts = opts || {
					"title": this.giveothertitle,
					"content": this.giveothercontant,
					"url": this.giveotherurl,
					"imageurl": this.giveotherimg
				};
				className = className || null;
				cordova.exec(sucFunc, failFunc, "SharePlugin", "start", [className, url, opts]);
			},
			//激活码解密
			getpassword(item) {
				var sessionId = localStorage.getItem('sessionId');
				let config = {
					url: window.api.customer_host + '/giftCardSalesAPI/decryptedActivationCode',
					method: 'GET',
					headers: {
						'sessionId': sessionId,
					},
					params: {
						activationCode: item.activationCode,
						giftcardEntityCode: item.giftcardEntityCode
					}
				};
				axios(config).then((res) => {
					if(res.data.returnCode == 1) {
						var passcode = res.data.data[0].activationCode
						//this.giveotherurl = `${location.origin + location.pathname + '#/main/ActivateGiftCard?giftcardEntityCode=' + item.giftcardEntityCode}`;
						this.giveotherurl = `${location.origin + location.pathname + '#/main/giftCardGuidance'}`;
						this.giveothercontant = '卡号：' + item.giftcardEntityCode + ' 激活码：' + passcode;
						this.giveotherimg = item.giftcardEntityImg || '';
						//console.log('7777777777',this.giveothercontant,this.giveotherurl,this.giveotherimg)
						/*第三部分享到微信*/
						this.SharePlugin(
							function(message) {
								if(message == '转增成功') {
									//分享成功后送礼                    
									console.log("转增成功");
								} else {
									//alert(message);
									return false;
								}
							},
							function(err) {
								console.log("Error: " + err);
							}
						);
					} else {
						this.mToastFn(res.data.msg);
					}
				})
			}
		},
		computed: {
			...mapGetters('wxh', [
				'userInfo'
			]),
			activeIndex() {
				return this.$store.state.cjy.classifyIndex
			},
			screenHeight() {
				return window.innerHeight - '80';
			},
			initData() {
				let arr1 = [];
				let arr2 = [];
				if(this.carddata) {
					for(let i = 0; i < this.carddata.length; i++) {
						if(this.carddata[i].activationStatus === 0) {
							arr1.push(this.carddata[i]);
						} else if(this.carddata[i].activationStatus === 1) {
							arr2.push(this.carddata[i]);
						}
					}
					this.titleInfor[0].goodsClassName = '未激活（' + arr1.length + "）";
					this.titleInfor[1].goodsClassName = '已激活（' + arr2.length + '）';
				}
				if(this.activeIndex == '0') {
					this.$refs.verticalScroll && this.$refs.verticalScroll.refresh();
					return arr1;
				} else if(this.activeIndex == '1') {
					this.$refs.verticalScroll && this.$refs.verticalScroll.refresh();
					return arr2;
				}
			}
		},
		created() {
			this.$store.dispatch('cjy/changeClassifyIndex', 0)
		},
		updated() {
			this.$nextTick(() => {
				setTimeout(() => {
					this.$refs.verticalScroll && this.$refs.verticalScroll.refresh();
				}, 500)
			});
			/*let heights = window.innerHeight;
            let widths = window.innerWidth;
            if(widths < 330){
                document.querySelector(".bottmar").style.paddingLeft = "0.1rem";
                document.querySelector(".bottmar").style.paddingRight = "0.1rem";
            }else{
            	document.querySelector(".bottmar").style.paddingLeft = "0.8rem";
                document.querySelector(".bottmar").style.paddingRight = "0.8rem";
            }*/
		},
		watch: {

		},
		mounted() {
			this.getcarddata();
			this.getInstrut()
		},
	}
</script>

<style>
	.overhid {
		overflow: hidden;
	}
	/*头部样式*/
	
	.myGiftCard_top {
		background: #fff;
		overflow: hidden;
		padding: 1rem;
		color: #9a9a9a;
	}
	
	.myGiftCard_top h1 {
		color: #EF5423;
		font-size: 1.6rem;
		font-weight: 400;
	}
	
	.myGiftCard .instructions {
		position: absolute;
		top: 1rem;
		right: 1rem;
	}
	/*礼品卡卡面信息展示*/
	
	.giftcard_list {
		padding-top: 1rem;
	}
	
	.giftcard_list li {
		width: 90%;
		margin: 0rem 5% 2rem 5%;
		position: relative;
	}
	
	.giftcard_list li .cardli {
		max-height: 11rem;
		min-height: 4.5rem;
		position: relative;
	}
	
	.giftcard_list li .cardli img {
		/* width: 100%; */
		width:16rem;
		max-height: 10rem;
		min-height: 0.56rem;
		margin:0 auto;
	}
	
	.giftcard_list li .cardli .cardhand {
		background-color: #fff;
		width: 86%;
		margin-left: 7%;
		position: absolute;
		bottom: -1.5rem;
		text-align: left;
		border-radius: 0.5rem;
		border: 1px solid #ccc;
		padding-bottom: 0.5rem;
	}
	
	.giftcard_list li .cardli .cardhand p {
		margin-top: 0.4rem;
		margin-left: 1rem;
		font-size: 0.65rem;
	}
	
	.giftcard_list li .cardli .cardhand .bottondiv {
		margin-top: 0.2rem;
		margin-bottom: 0.1rem;
	}
	
	.giftcard_list li .cardli .cardhand .bottondiv .botton {
		border: 1px solid #ccc;
		border-radius: 0.2rem;
		width: 6rem;
		text-align: center;
		height: 1.2rem;
		line-height: 1.2rem;
	}
	
	@media screen and (min-width: 330px) {
		.bottmar {
			padding: 0rem 0.8rem;
		}
	}
	@media screen and (max-width: 330px) {
		.bottmar {
			padding: 0rem 0.1rem;
		}
	}
	
	.giftcard_list li .cardli .cardhand .bottondiv .bottonred {
		color: #fff;
		background-color: #EF5423;
		border: none;
		float: right;
	}
	/*卡的操作（礼品卡的购买和激活按钮）*/
	
	.myGiftCard .cardoperation {
		position: fixed;
		bottom: 0rem;
		width: 100%;
		height: 2.5rem;
		line-height: 2.5rem;
		background-color: #fff;
		border-top: 1px solid #eee;
	}
	
	.myGiftCard .cardoperation span {
		display: inline-block;
		width: 50%;
		height: 2.5rem;
		line-height: 2.5rem;
		font-size: 0.8rem;
	}
	
	.myGiftCard .cardoperation span:last-child {
		background-color: #EF5423;
		color: #fff;
	}
	/*余额明细样式*/
	
	.aui-list .aui-list-item {
		border-top: 1px solid #f1f1f1;
	}
	
	.aui-media-list .aui-list-item-inner {
		text-align: left;
	}
	
	.aui-list .aui-list-item-title {
		display: inline-block;
		width: 70%;
		text-align: left;
	}
</style>